//
//  SWEditorPaintBlurToolbar.swift
//  ChildStory
//
//  Created by linhan on 2016/12/5.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWEditorPaintBlurToolbar: SWEditorExpandToolbar,CGImageDrawCanvasDelegate
{
    //预览时将图片缩小到优化尺寸(单倍分辨率下的尺寸)
    var optimizationSize:CGSize = CGSizeZero
    
    private var _image:UIImage?
    private let BlurAmount:CGFloat = 45
    private var _blurRadius:CGFloat = 6
    
    
    private var _change:Bool = false{
        didSet{
            if _change != oldValue
            {
                _confirmBtn.isEnabled = _change
            }
        }
    }
    
    
    private var _drawMode:DrawMode?
    {
        didSet{
            if let mode = _drawMode,mode != oldValue
            {
                _drawBtn.isSelected = mode == .Draw
                _eraseBtn.isSelected = mode == .Erase
                _canvas?.drawMode = mode
            }
        }
    }
    
    var lineWidth:CGFloat = 30{
        didSet{
            let Radius:CGFloat = BlurAmount * 0.3 + lineWidth * 0.5
            _cursor.frame = CGRectMake(0, 0, Radius * 2, Radius * 2)
            _cursor.center = _container.bounds.center
            _cursor.layer.cornerRadius = Radius
            _canvas?.lineWidth = lineWidth
        }
    }
    
    private var _originImageView:UIImageView = UIImageView()
    private var _blurImageView:UIImageView = UIImageView()
    private var _canvas:SWDrawMaskCanvas?
    private var _cursor:UIView = UIView()
    private var _container:UIView = UIView()
    private var _confirmBtn:UIButton = UIButton(type: .custom)
    lazy private var _drawBtn:UIButton = UIButton(type: .custom)
    lazy private var _eraseBtn:UIButton = UIButton(type: .custom)
    
    override init(frame: CGRect) {
        super.init(frame: CGRectMake(0, 0, frame.width, 140))
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit
    {
        print("DEINIT SWEditorPaintBlurToolbar")
    }

    override func toolbarDidAppear(_ animated: Bool)
    {
        if let image = image
        {
            //将图片缩小以加快滤镜的显示
            let retinaSize = image.retinaSize
            let originSize = image.originSize
            let containerSize = optimizationSize.multiply(2)
            let scale = ViewUtil.getAdaptiveScale(retinaSize.width, targetH: retinaSize.height, containerW: containerSize.width, containerH: containerSize.height)
            var size:CGSize = retinaSize
            if scale < 1
            {
                size = retinaSize.multiply(scale)
            }
            size = size.multiply(UIScreen.main.scale)
            //适中图
            _image = image.imageScaled(toConstrainSize: size)?.retinaImage ?? image.retinaImage
            
            canvasSetup()
        }
    }
    
    private func setup()
    {
        let LeftMargin:CGFloat = 38
        let RightMargin:CGFloat = 38
        
        let cancelBtn:UIButton = UIButton(type: .custom)
        cancelBtn.setImage(UIImage(named:"editor_icon_cancel"), for: .normal)
        cancelBtn.sizeToFit()
        cancelBtn.frame = CGRectMake(10, height - cancelBtn.height - 10, cancelBtn.width, cancelBtn.height)
        cancelBtn.addTarget(self, action: #selector(cancelBtnTapped), for: .touchUpInside)
        addSubview(cancelBtn)
        
        let confirmBtn:UIButton = UIButton(type: .custom)
        confirmBtn.setImage(UIImage(named:"editor_icon_ok"), for: .normal)
        confirmBtn.sizeToFit()
        confirmBtn.frame = CGRectMake(width - confirmBtn.width - 10, height - confirmBtn.height - 10, confirmBtn.width, confirmBtn.height)
        confirmBtn.addTarget(self, action: #selector(confirmBtnTapped(_:)), for: .touchUpInside)
        addSubview(confirmBtn)
        _confirmBtn = confirmBtn
        
        let StrokeIcon:UIImageView = UIImageView(image:UIImage(named:"editor_blur_icon_stroke"))
        StrokeIcon.frame = CGRectMake(LeftMargin, 0, StrokeIcon.width, StrokeIcon.height)
        addSubview(StrokeIcon)
        
        let SliderX:CGFloat = StrokeIcon.right + 25
        let SliderWidth:CGFloat = width - RightMargin - SliderX
        let SliderHeight:CGFloat = 30
        let strokeSlider:UISlider = UISlider(frame: CGRectMake(SliderX, (StrokeIcon.height - SliderHeight) * 0.5, SliderWidth, SliderHeight))
        strokeSlider.maximumValue = 100
        strokeSlider.value = 40
        strokeSlider.minimumValue = 25
        strokeSlider.addTarget(self, action: #selector(sliderValueChange(_:)), for: .valueChanged)
        strokeSlider.addTarget(self, action:#selector(sliderTouchUpInside(_:)), for:.touchUpInside)
        strokeSlider.addTarget(self, action:#selector(sliderTouchUpOutside(_:)), for:.touchUpOutside)
        strokeSlider.addTarget(self, action:#selector(sliderTouchDown(_:)), for:.touchDown)
        addSubview(strokeSlider)
        
        let StrengthIcon:UIImageView = UIImageView(image:UIImage(named:"editor_blur_icon_strength"))
        StrengthIcon.frame = CGRectMake(LeftMargin, StrokeIcon.bottom + 18, StrengthIcon.width, StrengthIcon.height)
        addSubview(StrengthIcon)
        
        let strengthSlider:UISlider = UISlider(frame: CGRectMake(SliderX, StrengthIcon.y + (StrengthIcon.height - SliderHeight) * 0.5, SliderWidth, SliderHeight))
        strengthSlider.maximumValue = 12
        strengthSlider.value = Float(_blurRadius)
        strengthSlider.minimumValue = 1
        strengthSlider.addTarget(self, action:#selector(strengthSliderTouchUp(_:)), for:.touchUpInside)
        strengthSlider.addTarget(self, action:#selector(strengthSliderTouchUp(_:)), for:.touchUpOutside)
        addSubview(strengthSlider)
        
        _cursor.layer.borderColor = UIColor.darkGray.cgColor
        _cursor.layer.borderWidth = 1.5
        _cursor.layer.masksToBounds = true
        _cursor.isHidden = true
        
        lineWidth = CGFloat(strokeSlider.value)
        
        let segmentedSize:CGSize = CGSizeMake(140, 60)
        let segmentedView:UIView = UIView()
        segmentedView.frame = CGRectMake((width - segmentedSize.width) * 0.5, height - segmentedSize.height, segmentedSize.width, segmentedSize.height)
        addSubview(segmentedView)
        
        
        let buttonSize:CGSize = CGSizeMake(28, 28)
        let drawBtn:UIButton = ButtonUtil.createTextImageVerticalButton("清晰笔", imageSize: buttonSize, fontSize: 12, gap: 3)
        drawBtn.setImage(UIImage(named:"editor_blur_btn_draw"), for: .normal)
        drawBtn.setTitleColor(UIColor.lightGray, for: .normal)
        drawBtn.setTitleColor(UIColor(hex:0xf99fbd), for: .selected)
        drawBtn.center = CGPointMake(drawBtn.width * 0.5, segmentedView.height * 0.5)
        drawBtn.addTarget(self, action: #selector(drawBtnTapped), for: .touchUpInside)
        segmentedView.addSubview(drawBtn)
        _drawBtn = drawBtn
        
        let eraseBtn = ButtonUtil.createTextImageVerticalButton("虚化笔", imageSize: buttonSize, fontSize: 12, gap: 3)
        eraseBtn.setImage(UIImage(named:"editor_blur_btn_erase"), for: .normal)
        eraseBtn.setTitleColor(UIColor.lightGray, for: .normal)
        eraseBtn.setTitleColor(UIColor(hex:0xf99fbd), for: .selected)
        eraseBtn.center = CGPointMake(segmentedView.width - eraseBtn.width * 0.5, segmentedView.height * 0.5)
        eraseBtn.addTarget(self, action: #selector(eraseBtnTapped), for: .touchUpInside)
        segmentedView.addSubview(eraseBtn)
        _eraseBtn = eraseBtn
        
        _drawMode = .Draw
    }
    
    private var _canvasScale:CGFloat = 1
    private func canvasSetup()
    {
        if let image = _image
        {
            let size:CGSize = canvas?.size ?? optimizationSize
            let scale:CGFloat = ViewUtil.getAdaptiveScale(image.size.width, targetH: image.size.height, containerW: size.width, containerH: size.height)
            _canvasScale = scale
            _container.frame = CGRectMake(0, 0, image.size.width, image.size.height)
            
            _blurImageView.image = image.blurredImage(_blurRadius, iterations: 3, ratio: 1, blendColor: nil, blendMode: .normal)
            _blurImageView.frame = _container.bounds
            _container.addSubview(_blurImageView)
            
            let imageView:UIImageView = UIImageView(image: image)
            imageView.frame = _container.bounds
            _container.addSubview(imageView)
            
            let maskCanvas = SWDrawMaskCanvas(frame: _container.bounds)
            maskCanvas.delegate = self
            maskCanvas.blurAmount = BlurAmount
            maskCanvas.backgroundColor = UIColor.clear
            maskCanvas.lineWidth = lineWidth
            _container.addSubview(maskCanvas)
            _canvas = maskCanvas
            
            let layer:CALayer = maskCanvas.shapeLayer
            let loveLayer:CAReplicatorLayer = CAReplicatorLayer()
            loveLayer.instanceCount = 3
            loveLayer.addSublayer(layer)
            
            imageView.layer.mask = loveLayer
            //view.layer.addSublayer(loveLayer)
            
            _container.addSubview(_cursor)
            
            _container.transform = CGAffineTransform(scaleX: scale, y: scale)
            canvas?.pluginCanvas = _container
        }
        
    }
    
    func CGImageDrawCanvasDrawBegan(_ canvas:SWDrawMaskCanvas, point:CGPoint)
    {
        _cursor.isHidden = false
        _cursor.center = CGPointMake(point.x + _blurImageView.x, point.y + _blurImageView.y)
    }
    
    func CGImageDrawCanvasDrawMoved(_ canvas:SWDrawMaskCanvas, point:CGPoint)
    {
        _cursor.center = CGPointMake(point.x + _blurImageView.x, point.y + _blurImageView.y)
    }
    
    func CGImageDrawCanvasDrawEnded(_ canvas:SWDrawMaskCanvas, point:CGPoint?)
    {
        _cursor.isHidden = true
    }
    
    @objc private func sliderValueChange(_ slider:UISlider)
    {
        lineWidth = CGFloat(slider.value)
    }
    
    @objc private func sliderTouchDown(_ slider:UISlider)
    {
        _cursor.center = _blurImageView.center
        _cursor.isHidden = false
    }
    
    @objc private func sliderTouchUpInside(_ slider:UISlider)
    {
        _cursor.isHidden = true
    }
    
    @objc private func sliderTouchUpOutside(_ slider:UISlider)
    {
        _cursor.isHidden = true
    }
    
    @objc private func strengthSliderTouchUp(_ slider:UISlider)
    {
        _blurRadius = CGFloat(slider.value)
        _blurImageView.image = _image?.blurredImage(_blurRadius, iterations: 3, ratio: 1, blendColor: nil,blendMode: CGBlendMode.normal)
    }
    
    @objc private func drawBtnTapped()
    {
        _drawMode = .Draw
    }
    
    @objc private func eraseBtnTapped()
    {
        _drawMode = .Erase
    }
    
    
    @objc private func confirmBtnTapped(_ button:UIButton)
    {
        canvas?.pluginCanvas = nil
        _container.transform = CGAffineTransform.identity
        if let image = _container.snapshotImage()
        {
            print("image:", image.size, image.scale)
            delegate?.expandToolbarConfirmed(image)
        }
    }
    
    @objc private func cancelBtnTapped()
    {
        if _change
        {
            canvas?.image = image
        }
        canvas?.pluginCanvas = nil
        delegate?.expandToolbarCancel()
    }
    
    
}
